import { Dialog, Toast } from 'qmp-component'
import { nativeHandler } from 'qmp-native'
import { formatURL } from '@/utils'
import { ImagePreview } from 'qmp-component'

function nativeDownLoad(params: any, callback?: any) {
  nativeHandler('downloadFiels', params)
    .then((res: any) => {
      Toast.success('下载成功')
      callback && callback()
    })
    .catch(() => {
      Toast.fail('下载失败')
      callback && callback()
    })
}

export const createDownload = (file: any) => {
  const { attachmentName, attachmentUrl, typeName } = file
  const downloadURL = formatURL(attachmentUrl)
  const onlineType = ['png', 'jpg', 'jpeg']
  const showCancelButton = onlineType.includes(typeName) // 是否可在线查看
  const params = { downloadURL, fileName: attachmentName }
  if (!showCancelButton) {
    nativeDownLoad(params)
    return
  }
  Dialog.confirm({
    title: '附件',
    message: attachmentName,
    lockScroll: true,
    confirmButtonText: '立即下载',
    cancelButtonText: '在线查看',
    showCancelButton,
    closeOnClickOverlay: true,
    beforeClose: (action: any) => {
      return new Promise((resolve) => {
        if (!action) {
          resolve(true)
          return
        }
        setTimeout(() => {
          if (action === 'confirm') {
            // 执行下载
            nativeDownLoad(params, () => {
              resolve(true)
            })
            resolve(true)
          } else if (action === 'cancel') {
            // 执行在线查看
            // 拦截取消操作
            // location.href = downloadURL
            ImagePreview([downloadURL])
            resolve(true)
          }
        }, 1000)
      })
    }
  })
}
